﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SummerTraining.OO;
using System.Collections;
using System.Net;
using System.IO.Compression;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace SummerTraining
{
    class Program
    {
        static void Main()
        {
            List<Exception> exceptions = new List<Exception>();
            exceptions.Add(new Exception());
            exceptions.Add(new MyException(""));

            foreach (Exception e in exceptions)
            {
                Console.WriteLine(e.Message);
            }
        }

        static void lib_OnBorrow(Library lib, LibraryEventArgs args)
        {
            args.Cancle = true;
        }

        static void WhenNewComing(object sender, EventArgs e)
        {
            StudentEventArgs arg = (StudentEventArgs)e;
            if (arg.Student.Gender == "male")
            {
                Console.WriteLine("欢迎你帅哥");
            }
            else
            {
                Console.WriteLine("欢迎你美女");
            }
        }

        static void c_NewComming(object sender, EventArgs e)
        {
            Class c = (Class)sender;
            StudentEventArgs arg = (StudentEventArgs)e;
            Console.WriteLine("着小子叫 " + arg.Student.Name);
            Console.WriteLine("已经有了" + c.Count + "个人了");
        }

        public static bool PreExam(Fruit f)
        {
            if (f is Apple)
            {
                return f.Weight > 200;
            }
            return true;
        }

        public static bool PreExam2(Fruit f)
        {
            Console.WriteLine(f.GetJuice());
            return true;
        }

        public static bool PosExam(Fruit f)
        {
            return f.GetJuice() > 100;
        }

        public static void Hello(string name)
        { 
            Console.WriteLine("come on," + name);
        }

        public static void DeleteByName(string name)
        {

        }

        public static void Serialize()
        {
            List<Goods> list = new List<Goods>();
            Goods g = new Goods();
            g.Id = "1";
            g.Name = "car";
            g.Owner = "johnny";
            g.Price = 5.4f;

            Goods g2 = new Goods();
            g2.Id = "2";
            g2.Name = "ball";
            g.Owner = "mike";
            g.Price = 10.7f;

            list.Add(g);
            list.Add(g2);

            //Stream binStream = File.Create(@"f:\goods.dat");
            //BinaryFormatter formatter = new BinaryFormatter();
            //formatter.Serialize(binStream, g);


            XmlSerializer xs = new XmlSerializer(typeof(List<Goods>));

            Stream s = File.OpenWrite(@"f:\goods.xml");
            xs.Serialize(s, list);
            s.Close();
        }

        public static void ReadFile()
        {
            FileStream fs = File.OpenRead(@"f:\my.dat");

            Stream s = File.Create(@"f:\tet.txt");

            GZipStream stream = new GZipStream(fs, CompressionMode.Decompress);

            //StreamReader reader = new StreamReader(stream);
            //string line;
            //while ((line = reader.ReadLine()) != null)
            //{
            //    Console.WriteLine(line);
            //}
            //reader.Close();
            int b = stream.ReadByte();
            while (b != -1)
            {
                s.WriteByte((byte)b);
                b = stream.ReadByte();
            }

            stream.Close();
            fs.Close();
        }

        public static void SaveFile()
        {
            FileStream sourceFile = File.Open(@"f:\scars.jmx", FileMode.Open);

            FileStream destFile = File.Create(@"f:\my.dat");

            GZipStream zipStream = new GZipStream(destFile, CompressionMode.Compress);


            int b = sourceFile.ReadByte();
            while (b != -1)
            {
                zipStream.WriteByte((byte)b);
                b = sourceFile.ReadByte();
            }

        }

        public static void IODemo()
        {
            //FileInfo fi = new FileInfo(@"E:\Visual Studio 2008\Projects\SummerTraining\SummerTraining\Student.cs");

            //StreamWriter sw = File.CreateText(@"f:\dest.txt");

            //StreamReader sr = fi.OpenText();
            //string line = sr.ReadLine();
            //while (line != null)
            //{
            //    sw.WriteLine(line);
            //    line = sr.ReadLine();
            //}

            //sr.Close();
            //sw.Close();

            //FileStream fs = new FileStream(@"f:\cndemo.txt", 
            //    FileMode.Open, FileAccess.Read);
        }

        public static void PrintDir(DirectoryInfo di)
        {
            FileInfo[] fis = di.GetFiles();

            foreach (FileInfo fi in fis)
            {
                Console.WriteLine(fi.FullName);


                
            }
            DirectoryInfo[] dis = di.GetDirectories();
            foreach (DirectoryInfo d in dis)
            {
                PrintDir(d);
            }
        }

        public static void GenericDemo()
        {
            List<string> names = new List<string>();

            names.Add("a");
            names.Add("b");

            string s = names[0];
            Console.WriteLine(s);

            Dictionary<string, int> dic = new Dictionary<string, int>();
            dic.Add("one", 1);
            dic.Add("two", 2);
            int i = dic["one"];



            Console.WriteLine(i);
        }

    }

    class MyComparer : IComparer
    {
        private bool asc;
        private int field;
        public MyComparer(int field, bool asc)
        {
            this.field = field;
            this.asc = asc;
        }

        #region IComparer Members

        int IComparer.Compare(object x, object y)
        {
            string s1 = x.ToString();
            string s2 = y.ToString();

            if (field == 1)
                return asc ? s1.CompareTo(s2) : -s1.CompareTo(s2);
            else
                return asc ? s1.Length.CompareTo(s2.Length) : -s1.Length.CompareTo(s2.Length);

        }

        #endregion
    }




    public class DeflateTest
    {
        public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
        {
            // Use this method is used to read all bytes from a stream.
            int offset = 0;
            int totalCount = 0;
            while (true)
            {
                int bytesRead = stream.Read(buffer, offset, 100);
                if (bytesRead == 0)
                {
                    break;
                }
                offset += bytesRead;
                totalCount += bytesRead;
            }
            return totalCount;
        }

        public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
        {
            // Use this method to compare data from two different buffers.
            if (len1 != len2)
            {
                Console.WriteLine("Number of bytes in two buffer are different {0}:{1}", len1, len2);
                return false;
            }

            for (int i = 0; i < len1; i++)
            {
                if (buf1[i] != buf2[i])
                {
                    Console.WriteLine("byte {0} is different {1}|{2}", i, buf1[i], buf2[i]);
                    return false;
                }
            }
            Console.WriteLine("All bytes compare.");
            return true;
        }

        public static void DeflateCompressDecompress(string filename)
        {
            Console.WriteLine("Test compression and decompression on file {0}", filename);
            FileStream infile;
            try
            {
                // Open the file as a FileStream object.
                infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] buffer = new byte[infile.Length];
                // Read the file to ensure it is readable.
                int count = infile.Read(buffer, 0, buffer.Length);
                if (count != buffer.Length)
                {
                    infile.Close();
                    Console.WriteLine("Test Failed: Unable to read data from file");
                    return;
                }
                infile.Close();
                MemoryStream ms = new MemoryStream();
                // Use the newly created memory stream for the compressed data.
                DeflateStream compressedzipStream = new DeflateStream(ms, CompressionMode.Compress, true);
                Console.WriteLine("Compression");
                compressedzipStream.Write(buffer, 0, buffer.Length);
                // Close the stream.
                compressedzipStream.Close();
                Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);

                // Reset the memory stream position to begin decompression.
                ms.Position = 0;
                DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress);
                Console.WriteLine("Decompression");
                byte[] decompressedBuffer = new byte[buffer.Length + 100];
                // Use the ReadAllBytesFromStream to read the stream.
                int totalCount = DeflateTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
                Console.WriteLine("Decompressed {0} bytes", totalCount);

                if (!DeflateTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount))
                {
                    Console.WriteLine("Error. The two buffers did not compare.");
                }
                zipStream.Close();
            } // end try
            catch (InvalidDataException)
            {
                Console.WriteLine("Error: The file being read contains invalid data.");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("Error:The file specified was not found.");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Error: path is a zero-length string, contains only white space, or contains one or more invalid characters");
            }
            catch (PathTooLongException)
            {
                Console.WriteLine("Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.");
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine("Error: The specified path is invalid, such as being on an unmapped drive.");
            }
            catch (IOException)
            {
                Console.WriteLine("Error: An I/O error occurred while opening the file.");
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine("Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.");
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Error: You must provide parameters for MyGZIP.");
            }
        }
    }







}
